﻿namespace Devonline.Utils;

public static class FileUtility
{
    /// <summary>
    /// 缓冲区大小
    /// </summary>
    private const int BUFFER_SIZE = AppSettings.UNIT_KILO;
    /// <summary>
    /// 销毁文件, 销毁后的文件不可还原
    /// </summary>
    /// <param name="fileName">要销毁的文件名</param>
    /// <param name="filler">默认填充符, 默认: 0x00</param>
    /// <param name="delete">是否删除, 默认: 是</param>
    /// <returns></returns>
    public static async Task FileDestoryAsync(string fileName, byte filler = 0x00, bool delete = true)
    {
        if (!File.Exists(fileName))
        {
            throw new FileNotFoundException("文件不存在!", fileName);
        }

        var fileInfo = new FileInfo(fileName);
        var bufferLength = (int)((fileInfo.Length >= BUFFER_SIZE) ? BUFFER_SIZE : fileInfo.Length);
        var last = fileInfo.Length;
        var buffer = new byte[bufferLength];
        for (int index = AppSettings.UNIT_ZERO; index < bufferLength; index++)
        {
            buffer[index] = filler;
        }

        using var fs = fileInfo.Open(FileMode.Open, FileAccess.Write);
        fs.Position = AppSettings.UNIT_ZERO;
        while (last >= bufferLength)
        {
            await fs.WriteAsync(buffer.AsMemory(AppSettings.UNIT_ZERO, bufferLength)).ConfigureAwait(false);
            last -= bufferLength;
        }

        if (last > AppSettings.UNIT_ZERO)
        {
            await fs.WriteAsync(buffer.AsMemory(AppSettings.UNIT_ZERO, (int)last)).ConfigureAwait(false);
        }

        fs.Close();
        await fs.DisposeAsync().ConfigureAwait(true);

        if (delete)
        {
            fileInfo.Delete();
        }
    }
}